<?php

namespace app\admin\service;

use app\common\HugeAmountClient;
use app\model\Videos;
// use think\facade\Session;
use app\model\User;
use app\model\PayRecord;
use think\facade\Cache;

class IndexService
{
    private $videosModel;
    private $userModel;
    private $payRecordModel;

    public function __construct(Videos $videosModel, User $userModel, PayRecord $payRecordModel)
    {
        $this->videosModel = $videosModel;
        $this->userModel = $userModel;
        $this->payRecordModel = $payRecordModel;
    }

    // 获取首页数据
    public function getAdminHomePageData()
    {
        $redis = Cache::store('redis')->handler();
        $redis->select(2);
        $data = json_decode($redis->get('index_getAdminHomePageData'), true);
        if(!empty($data)) {
            return $data;
        }
        // 短剧总数
        // $videoTotal = $this->videosModel->where(['is_delete' => 0])->count();

        // 会员数
        $where = [
            ['is_delete', '=', 0],
            ['is_members', '=', 1],
            ['expiration_time', '>', time()],
        ];
        $memberTotal = $this->userModel->where($where)->count();

        $toDay = date('Ymd');
        // 今日新增用户数
        $toDayNewUserData = $this->userModel->where(['register_date' => $toDay])->field('id')->select()->toArray();

        $toDayNewUser = count($toDayNewUserData);
        // $uids = array_column($toDayNewUserData, 'id');

        $startDate = date('Ym', time()) . '01';
        $endDate = date('Ymt', time());
        // 本月新增用户数
        $where = [
            ['register_date', '>=', $startDate],
            ['register_date', '<=', $endDate]
        ];
        $thisMonthNewUser = $this->userModel->where($where)->count();

        // 今日用户充值数据
        $toDayUserRechargeData = $this->payRecordModel->where([['consume_date', '=', $toDay], ['total_fee', '>', 0]])->field('uid, status, total_fee, type, activation_date')->select();
        $toDayUserRecharge = $toDayPaidRecharge = $toDayUnpaidRecharge = $toDayRechargeAmount = $toDayNewUserRechargeAmount = $toDayMemberNum = 0;
        foreach ($toDayUserRechargeData as $key => $value) {
            // 今日用户充值数
            $toDayUserRecharge = $toDayUserRecharge + 1;

            if ($value['status'] == 1) {
                // 今日已支付充值数
                $toDayPaidRecharge = $toDayPaidRecharge + 1;
                // 今日充值金额
                $toDayRechargeAmount = $toDayRechargeAmount + $value['total_fee'];
                // 今日新用户充值金额
                if ($value['activation_date'] == $toDay) {
                    $toDayNewUserRechargeAmount = $toDayNewUserRechargeAmount + $value['total_fee'];
                }
            } else {
                // 今日未支付充值数
                $toDayUnpaidRecharge = $toDayUnpaidRecharge + 1;
            }
            if (in_array($value['type'], [2, 3, 4, 5, 6, 7, 8, 11])) {
                $toDayMemberNum += 1;
            }
        }

        // 今日充值率
        $toDayRechargeRate = $toDayUserRecharge != 0 ? round($toDayPaidRecharge / $toDayUserRecharge * 100, 2) . '%' : '0%';

        $yesterDay = date('Ymd', time() - 24 * 60 * 60);
        // 昨日充值金额
        $yesterDayRechargeAmount = 0;

        $yesterDayNewUserIds = $this->userModel->where(['register_date' => $yesterDay])->column('id');
        // 昨日新用户充值
        $yesterDayNewUserRechargeAmount = 0;

        // 本月充值金额（不含当日）
        $thisMonthRechargeAmount = 0;

        // 累计充值金额（不含当日）
        $where = [
            ['consume_date', '<', date('Ymd')],
            ['status', '=', 1]
        ];
        $getAmount = json_decode($redis->get('index_accumulatedRechargeAmount'), true);
        if(empty($getAmount)) {
            $accumulatedRechargeAmount = $this->payRecordModel->getSumPrice($where); // 累计充值金额（不含当日）

            // 本月
            $theMonthWhere = [
                ['consume_date', '<', date('Ymd')],
                ['consume_date', '>=', $startDate],
                ['status', '=', 1]
            ];
            $totalRecharge = $this->payRecordModel->getInfo($theMonthWhere, 'consume_date, total_fee, uid');
            foreach ($totalRecharge as $key => $value) {

                $thisMonthRechargeAmount = $thisMonthRechargeAmount + $value['total_fee']; // 本月充值金额（不含当日）

                if ($value['consume_date'] == $yesterDay) {
                    $yesterDayRechargeAmount = $yesterDayRechargeAmount + $value['total_fee']; // 昨日充值金额
                    if (in_array($value['uid'], $yesterDayNewUserIds)) {
                        $yesterDayNewUserRechargeAmount = $yesterDayNewUserRechargeAmount + $value['total_fee']; // 昨日新用户充值金额
                    }
                }
            }

            $redis = Cache::store('redis')->handler();
            $redis->select(5);
            // 
            $redisCostData = [];
            $redisCostData1 = $redis->get('oceanengine_business_ad_data_today:18006505024 '); // 杭州泉起抖小
            $redisCostData2 = $redis->get('oceanengine_business_ad_data_today:sybyn6'); // 杭州泉起
            $redisCostData3 = $redis->get('oceanengine_business_ad_data_today:sybyn1'); // 泉起-抖小-艺达
    
            $redisCostDataLiuYi = json_decode($redisCostData1, true);
            $redisCostDataGuangZhou = json_decode($redisCostData2, true);
            $redisCostDataThree= json_decode($redisCostData3, true);
            if (!empty($redisCostDataLiuYi['data'])) {
                $redisCostData = $redisCostData + $redisCostDataLiuYi['data'];
            }
            if (!empty($redisCostDataGuangZhou['data'])) {
                $redisCostData = $redisCostData + $redisCostDataGuangZhou['data'];
            }
            if (!empty($redisCostDataThree['data'])) {
                $redisCostData = $redisCostData + $redisCostDataThree['data'];
            }
            $totalCost = $totalShowNum = 0;
            foreach ($redisCostData as $key => $value) {
                $totalCost += $value['stat_cost'];
                $totalShowNum += $value['show_cnt'];
            }
            $extime = strtotime(date('Y-m-d', strtotime('+1 day')) . ' 00:00:00');
            $redis->set('index_accumulatedRechargeAmount', json_encode([
                'thisMonthRechargeAmount' => $thisMonthRechargeAmount,
                'yesterDayRechargeAmount' => $yesterDayRechargeAmount,
                'yesterDayNewUserRechargeAmount' => $yesterDayNewUserRechargeAmount,
                'accumulatedRechargeAmount' => $accumulatedRechargeAmount,
                'totalCost'=>$totalCost,
                'totalShowNum'=>$totalShowNum
            ]), $extime - time());
        } else {
            $thisMonthRechargeAmount = $getAmount['thisMonthRechargeAmount'];
            $yesterDayRechargeAmount = $getAmount['yesterDayRechargeAmount'];
            $yesterDayNewUserRechargeAmount = $getAmount['yesterDayNewUserRechargeAmount'];
            $accumulatedRechargeAmount = $getAmount['accumulatedRechargeAmount'];
            $totalCost = $getAmount['totalCost'];
            $totalShowNum = $getAmount['totalShowNum'];
        }
        $result = [
            // 'video_total'                        => $videoTotal,
            'total_cost'                         => round($totalCost, 2),
            'total_show_num'                     => $totalShowNum,
            'member_total'                       => $memberTotal,
            'today_new_user'                     => $toDayNewUser,
            'this_month_new_user'                => $thisMonthNewUser,
            'today_user_recharge'                => $toDayUserRecharge,
            'today_paid_recharge'                => $toDayPaidRecharge,
            'today_unpaid_recharge'              => $toDayUnpaidRecharge,
            'today_recharge_rate'                => $toDayRechargeRate,
            'today_member_num'                   => $toDayMemberNum, // 今日会员
            'today_recharge_amount'              => round($toDayRechargeAmount, 2),
            'to_day_new_user_recharge_amount'    => round($toDayNewUserRechargeAmount, 2), // 今日新用户充值
            'to_day_old_user_recharge_amount'    => round($toDayRechargeAmount - $toDayNewUserRechargeAmount, 2), // 今日老用户充值
            'yesterday_recharge_amount'          => round($yesterDayRechargeAmount, 2),
            'yesterday_new_user_recharge_amount' => round($yesterDayNewUserRechargeAmount, 2),
            'this_month_recharge_amount'         => round($thisMonthRechargeAmount, 2),
            'accumulated_recharge_amount'        => round($accumulatedRechargeAmount, 2)
        ];
        $redis->set('index_getAdminHomePageData', json_encode($result), 10 * 60);
        return $result;
    }

    // 获取后台首页充值曲线图数据
    public function getAdminHomePageCurveData($params)
    {
        $where[] = ['status', '=', 1];
        if (!empty($params['start_date'])) {
            $startDate = intval(str_replace('-', '', $params['start_date']));
        } else {
            $startDate = date('Ym', time()) . '01';
        }

        $where[] = ['consume_date', '>=', $startDate];

        if (!empty($params['end_date'])) {
            $endDate = intval(str_replace('-', '', $params['end_date']));
        } else {
            $endDate = date('Ymt', time());
        }

        $where[] = ['consume_date', '<=', $endDate];
        $redis = Cache::store('redis')->handler();
        $redis->select(2);
        $key='index_payRecordModel'.$startDate.'-'.$endDate;
        $payRecordModel=json_decode($redis->get($key),true);
        $totalFeeData = $result = [];
        if(empty($payRecordModel)){
            $data = $this->payRecordModel->getInfo($where, 'consume_date, total_fee');
            foreach ($data as $item) {
                $totalFeeData[$item['consume_date']]=empty($totalFeeData[$item['consume_date']])? $item['total_fee']:$totalFeeData[$item['consume_date']]+$item['total_fee'];
            }
            $extime=strtotime(date('Y-m-d',strtotime('+1 day')).' 00:00:00');
            $redis->set($key,json_encode([
                'totalFeeData'=>$totalFeeData
            ]),$extime-time());
        }else{
            $totalFeeData=$payRecordModel['totalFeeData'];
        }

        $startDate = substr($startDate, 0, 4) . '-' . substr($startDate, 4, 2) . '-' . substr($startDate, 6, 2);
        $endDate = substr($endDate, 0, 4) . '-' . substr($endDate, 4, 2) . '-' . substr($endDate, 6, 2);

        $second = 86400;
        $timeDiff = (strtotime($endDate . ' +1 day') - strtotime($startDate)) / $second;

        for ($i = 0; $i < $timeDiff; $i++) {
            $date = date('Ymd', strtotime($startDate) + $i * $second);
            $dateString = date('Y-m-d', strtotime($startDate) + $i * $second);
            $result[$dateString] = !empty($totalFeeData[$date]) ? round($totalFeeData[$date], 2) : 0;
        }

        return $result;
    }

    // 获取后台首页消耗曲线图数据
    public function getTotalCost()
    {
        //
    }
}
